package logic

import (
	"context"
	"errors"
	"house-info-net/houserpc/houserpc"
	"house-info-net/houserpc/internal/svc"
	"house-info-net/models/cache"
	"house-info-net/models/mysql"
	"house-info-net/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *houserpc.UpdatePasswordRequest) (*houserpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	if err := user.FindUserByUserId(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}
	if pkg.Md5(in.OldPassword) != user.Password {
		return nil, errors.New("原密码输入错误,请重新输入")
	}
	if in.NewPassword != in.AckNewPassword {
		return nil, errors.New("两次密码输入不一致,请重新输入")
	}
	if in.NewPassword == in.OldPassword {
		return nil, errors.New("原密码与新密码一致,请重新输入")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+user.Mobile).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误,请重新输入")
	}

	user.Password = pkg.Md5(in.NewPassword)
	if err := user.UpdateUser(mysql.DB); err != nil {
		return nil, errors.New("修改失败")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+user.Mobile)
	
	return &houserpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
